from odoo import http, _
from odoo.http import request
import json
import logging

_logger = logging.getLogger(__name__)


class ProductTemplateController(http.Controller):
    @http.route("/api/product/code", auth='user', type='http', methods=['GET'], csrf=True)
    def get_default_code(self, **kwargs):
        """
        获取默认编码
        :param kwargs:
        :return:
        """
        _logger.info('get_default_code, 提交参数: %s' % kwargs)
        code = kwargs.get('code')
        if not code:
            return request.make_json_response({'code': 400, 'msg': _('code required')})
        domain = ['|', ('default_code', '=', code), ("product_variant_ids.default_code", "=", code)]
        product = request.env['product.template'].sudo().search(domain, limit=1)
        if not product:
            return request.make_json_response({'code': 400, 'msg': _('code %s not found') % code})
        data = {
            'id': product.id,
            'code': product.default_code,
            'name': product.name,
            'description_eng': product.description_eng,
            'uom_id': product.uom_id.name,
            'uom_po_id': product.uom_po_id.name,
            'specification_chi': product.specification_chi,
            'specification_eng': product.specification_eng,
            'standards': product.standards,
            'categ_id': product.categ_id.display_name,
            'versions': product.versions,
            'application_product_id': product.application_product_id.name,
        }
        return http.Response(json.dumps({'code': 200, 'msg': 'success', 'data': data}), status=200,
                             mimetype='application/json')

    @http.route("/api/product/template", auth='user', type='json', methods=['POST'], csrf=True, cors='*')
    def product_template_post(self, **kwargs):
        """
        新建成品和产品升级
        """
        api_records = {
            'api_params': kwargs,
            'api_user_id': False,
            'api_route': '/api/product/template',
            'state': 'success',
            'result_json': False
        }
        request.env['api.records'].sudo().create(api_records)
        _logger.info('product_template_post, 提交参数: %s' % kwargs)
        if not kwargs:
            return {'code': 400, 'msg': _('params required')}
        code = kwargs.get('product_code') or ''
        name = kwargs.get('product_name') or ''
        if not code or not name:
            return {'code': 400, 'msg': _('product_code and product_name required')}
        version = kwargs.get('product_version') or ''
        if not version:
            return {'code': 400, 'msg': _('product version required')}
        materiel_status = kwargs.get('materiel_status') or "S"
        if not materiel_status:
            return {'code': 400, 'msg': _('materiel_status required')}
        product = request.env['product.template'].sudo().search([('default_code', '=', code)], limit=1)
        if product:
            return {'code': 400, 'msg': _('product code %s already exists') % code}
        application_id = kwargs.get('application_product_id') or False
        if application_id:
            application = request.env['application.product'].sudo().search([('name', '=', application_id)],
                                                                           limit=1)
            if not application:
                application = request.env['application.product'].create({'name': application_id})
            application_id = application.id
        product_id = kwargs.get('product_id')
        if not product_id:
            return {'code': 400, 'msg': _('product_id %s required') % code}
        cus_product = request.env['product.template'].sudo().browse(product_id)
        if not cus_product:
            return {'code': 400, 'msg': _('product id %s not found') % product_id}
        try:
            product = cus_product.copy()
            # 产品已升级, 禁用下卡、下单
            cus_product.write({
                's_disable_down_card': True,
                's_disable_order': True
            })
            item_code_ids = []
            for item in cus_product.customer_item_code_ids:
                domain = [('customer_id', '=', item.customer_id.id),
                          ('product_id', '=', product.id),
                          ('version', '=', item.version),
                          ('code', '=', item.code)]
                tm = request.env['customer.item.code'].sudo().search(domain)
                if tm:
                    item_code_ids.append(tm.id)
                else:
                    item_code = request.env['customer.item.code'].sudo().create({
                        'code': item.code,
                        'product_id': product.id,
                        'customer_id': item.customer_id.id,
                        'customer_item_desc': item.customer_item_desc,
                        'version': item.version,
                        'recent_price': item.recent_price,
                    })
                    item_code_ids.append(item_code.id)
            product.write({
                'name': name,
                'default_code': code,
                'versions': version,
                's_disable_down_card': True,
                's_disable_order': True,
                'active': True,
                'jmi_author': kwargs.get('jmi_author'),
                'application_product_id': application_id,
                'customer_item_code_ids': [(6, 0, item_code_ids)]
            })
        except Exception as e:
            _logger.error('product_template_post, 创建失败: %s' % e)
            api_records['state'] = 'fail'
            api_records['result_json'] = str(e)
            return {'code': 400, 'msg': _('产品复制失败')}
        # else:
        #     finished_categ = request.env.ref('sb_sale.finished_product_type')
        #     manufacturing_route_id = request.env.ref('mrp.route_warehouse0_manufacture')
        #     data = {
        #         'name': name,
        #         'default_code': code,
        #         'versions': version,
        #         'jmi_author': kwargs.get('jmi_author'),
        #         'uom_id': request.env.ref('pcbmanufact.uom_part').id,
        #         'uom_po_id': request.env.ref('pcbmanufact.uom_part').id,
        #         'categ_id': finished_categ.id,
        #         'route_ids': [(4, manufacturing_route_id.id)],
        #         'detailed_type': 'product',
        #         'materiel_status': materiel_status,
        #         'application_product_id': application_id,
        #     }
        #     product = request.env['product.template'].create(data)
        #     product._onchange_route_ids()
        # # 需要创建BOM
        # bom_ids = request.env['mrp.bom'].sudo().search([('product_tmpl_id', '=', product.id)])
        # if not bom_ids:
        #     bom_dict = {
        #         'product_tmpl_id': product.id,
        #         'code': product.default_code,
        #         'product_uom_id': product.uom_id.id,
        #         'type': 'normal',
        #     }
        #     request.env['mrp.bom'].create(bom_dict)
        return {'code': 200, 'msg': 'success', 'id': product.id}

    @http.route("/api/product/coding/attribute", auth='user', type='http', methods=['GET'], csrf=True, cors='*')
    def product_coding_attribute(self, **kwargs):
        categ = kwargs.get('categ')
        if not categ:
            return request.make_json_response({'code': 400, 'msg': _('categ required')})
        categ_ids = request.env['product.category'].sudo().search([('code', '=', categ)])
        categ_ids |= categ_ids.child_id
        domain = [('categ_id', 'in', categ_ids.ids), ('s_jmi_upload', '=', False)]
        product_ids = request.env['product.template'].sudo().search(domain)
        data = []
        for record in product_ids:
            coding_ids = record.product_template_coding_attribute_ids
            if not coding_ids:
                continue
            coding_attribute_ids = []
            for rec in coding_ids:
                coding_attribute_ids.append({
                    'name': rec.name,
                    'input_value': rec.input_value or '',
                    'code': rec.material_coding_attribute_value_code or '',
                })
            data.append({
                'product_id': record.id,
                'name': record.name,
                'coding_attribute_ids': coding_attribute_ids
            })
        return request.make_json_response({'code': 200, 'msg': 'success', 'data': data})

    @http.route("/api/product/coding/attribute/post", auth='user', type='json', methods=['POST'], csrf=True, cors='*')
    def product_coding_attribute_post(self, **kwargs):
        """
        上传产品id, 批量更改状态
        """
        product_ids = kwargs.get('product_ids')
        if product_ids:
            res = request.env['product.template'].sudo().browse(product_ids)
            for r in res:
                r.write({'s_jmi_upload': True})
        return {'code': 200, 'msg': 'success'}
